import http from './http'

// 课程相关接口
export interface Course {
  id: number
  title: string
  description: string
  coverUrl?: string
  categoryId?: number
  price: number
  enrollmentCount: number
  averageRating: number
  reviewCount: number
  difficulty: 'BEGINNER' | 'INTERMEDIATE' | 'ADVANCED'
  teacherId: number
  teacherName?: string
  status: 'DRAFT' | 'PUBLISHED' | 'ARCHIVED'
  createdAt: string
  updatedAt: string
}

export interface Category {
  id: number
  name: string
  description?: string
  parentId?: number
  sortOrder: number
  courseCount?: number
  children?: Category[]
}

export interface CourseSearchParams {
  keyword?: string
  categoryId?: number
  difficulty?: string
  minPrice?: number
  maxPrice?: number
  sortBy?: string
  page?: number
  pageSize?: number
}

export interface Lesson {
  id: number
  courseId: number
  title: string
  lessonType: 'VIDEO' | 'DOCUMENT' | 'QUIZ' | 'ASSIGNMENT'
  isFree: boolean
  contentUrl?: string
  videoUrl?: string
  duration: number
  orderNo: number
}

export interface CourseRequest {
  title: string
  description: string
  categoryId: number
  price: number
  difficulty: 'BEGINNER' | 'INTERMEDIATE' | 'ADVANCED'
  coverImageUrl?: string
}

export interface LessonRequest {
  title: string
  lessonType: 'VIDEO' | 'DOCUMENT' | 'QUIZ' | 'ASSIGNMENT'
  isFree: boolean
  contentUrl?: string
  videoUrl?: string
  duration: number
  orderNo: number
}

export const courseApi = {
  // 获取课程列表（支持搜索和过滤）
  getCourses(params: CourseSearchParams = {}): Promise<any> {
    return http.get('/v1/courses', { params })
  },

  // 获取课程详情
  getCourseDetail(id: number): Promise<Course> {
    return http.get(`/v1/courses/${id}`)
  },

  // 获取课程章节
  getCourseLessons(id: number): Promise<Lesson[]> {
    return http.get(`/v1/courses/${id}/lessons`)
  },

  // 获取热门课程
  getPopularCourses(page = 1, pageSize = 10): Promise<any> {
    return http.get('/v1/courses', { params: { sortBy: 'popular', page, pageSize } })
  },

  // 获取最新课程
  getLatestCourses(page = 1, pageSize = 10): Promise<any> {
    return http.get('/v1/courses', { params: { sortBy: 'latest', page, pageSize } })
  },

  // 获取分类
  getCategories(): Promise<Category[]> {
    return http.get('/v1/categories')
  },

  // 获取分类树
  getCategoryTree(): Promise<Category[]> {
    return http.get('/v1/categories/tree')
  },

  // 教师端 API
  // 获取教师的课程列表
  getTeacherCourses(params: any = {}): Promise<any> {
    return http.get('/v1/teacher/courses', { params }).then((response: any) => {
      // 将后端的 coverUrl 映射为前端的 coverImageUrl 以保持一致性
      if (response.content) {
        response.content = response.content.map((course: any) => ({
          ...course,
          coverImageUrl: course.coverUrl
        }))
      }
      return response
    })
  },

  // 创建课程
  createCourse(data: CourseRequest): Promise<Course> {
    // 后端字段为 coverUrl，这里做一次名称映射
    const payload: any = { ...data, coverUrl: (data as any).coverImageUrl }
    delete payload.coverImageUrl
    delete payload.status // 后端不支持status字段，需要删除
    return http.post('/v1/courses', payload)
  },

  // 更新课程
  updateCourse(id: number, data: CourseRequest): Promise<Course> {
    const payload: any = { ...data, coverUrl: (data as any).coverImageUrl }
    delete payload.coverImageUrl
    delete payload.status // 后端不支持status字段，需要删除
    return http.put(`/v1/courses/${id}`, payload)
  },

  // 删除课程
  deleteCourse(id: number): Promise<void> {
    return http.delete(`/v1/courses/${id}`)
  },

  // 发布课程
  publishCourse(id: number): Promise<void> {
    // 后端发布接口为 /api/v1/courses/{id}/publish (POST)
    return http.post(`/v1/courses/${id}/publish`)
  },

  // 下线课程
  unpublishCourse(id: number): Promise<void> {
    return http.put(`/v1/courses/${id}/unpublish`)
  },

  // 获取教师课程详情（包含编辑权限的详细信息）
  getTeacherCourseDetail(id: number): Promise<Course> {
    return http.get(`/v1/courses/${id}`).then((course: any) => ({
      ...course,
      coverImageUrl: course.coverUrl
    }))
  }
}

// 课程章节管理 API
export const lessonApi = {
  // 获取课程章节列表
  getCourseLessons(courseId: number): Promise<Lesson[]> {
    // 后端接口：GET /api/v1/courses/{id}/lessons
    return http.get(`/v1/courses/${courseId}/lessons`)
  },

  // 创建章节
  createLesson(courseId: number, data: LessonRequest): Promise<Lesson> {
    // 后端接口：POST /api/v1/courses/{id}/lessons
    return http.post(`/v1/courses/${courseId}/lessons`, data)
  },

  // 更新章节
  updateLesson(courseId: number, lessonId: number, data: LessonRequest): Promise<Lesson> {
    // 后端接口：PUT /api/v1/courses/lessons/{lessonId}
    return http.put(`/v1/courses/lessons/${lessonId}`, data)
  },

  // 删除章节
  deleteLesson(courseId: number, lessonId: number): Promise<void> {
    // 后端接口：DELETE /api/v1/courses/lessons/{lessonId}
    return http.delete(`/v1/courses/lessons/${lessonId}`)
  },

  // 重排序章节
  reorderLessons(courseId: number, lessonIds: number[]): Promise<void> {
    // 后端暂未提供接口，此处直接返回已完成的Promise作为占位
    return Promise.resolve()
  }
}

// 文件上传 API
export const uploadApi = {
  // 上传课程封面
  uploadCourseCover(file: File): Promise<{ url: string }> {
    const formData = new FormData()
    formData.append('file', file)
    // 后端接口为 /v1/upload/cover，返回 { coverUrl }
    return http
      .post('/v1/upload/cover', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then((data: any) => ({ url: data.coverUrl }))
  },

  // 上传视频
  uploadVideo(file: File, onProgress?: (progress: number) => void): Promise<{ url: string }> {
    const formData = new FormData()
    formData.append('file', file)
    // 后端统一使用 /v1/upload/lesson-content，返回 { contentUrl }
    return http
      .post('/v1/upload/lesson-content', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 600000, // 10分钟超时，适合2GB视频文件
        onUploadProgress: onProgress
          ? (progressEvent) => {
              if (progressEvent.total) {
                const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
                onProgress(progress)
              }
            }
          : undefined
      })
      .then((data: any) => ({ url: data.contentUrl }))
  },

  // 上传文档
  uploadDocument(file: File): Promise<{ url: string }> {
    const formData = new FormData()
    formData.append('file', file)
    // 与视频相同的后端接口
    return http
      .post('/v1/upload/lesson-content', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then((data: any) => ({ url: data.contentUrl }))
  }
}

// 课程评价接口
export interface CourseReview {
  id: number
  userId: number
  username: string
  userAvatar?: string
  courseId: number
  rating: number
  comment?: string
  createdAt: string
  updatedAt: string
}

export interface CourseReviewRequest {
  rating: number
  comment?: string
}

export const courseReviewApi = {
  // 获取课程评价列表
  getCourseReviews(courseId: number, page = 1, pageSize = 10): Promise<any> {
    return http.get(`/v1/courses/${courseId}/reviews`, { params: { page, pageSize } })
  },

  // 提交评价
  createReview(courseId: number, data: CourseReviewRequest): Promise<CourseReview> {
    return http.post(`/v1/courses/${courseId}/reviews`, data)
  },

  // 更新评价
  updateReview(courseId: number, reviewId: number, data: CourseReviewRequest): Promise<CourseReview> {
    return http.put(`/v1/courses/${courseId}/reviews/${reviewId}`, data)
  },

  // 删除评价
  deleteReview(courseId: number, reviewId: number): Promise<void> {
    return http.delete(`/v1/courses/${courseId}/reviews/${reviewId}`)
  },

  // 检查是否已评价
  checkUserReview(courseId: number): Promise<boolean> {
    return http.get(`/v1/courses/${courseId}/reviews/check`)
  },

  // 获取用户评价
  getUserReview(courseId: number): Promise<CourseReview> {
    return http.get(`/v1/courses/${courseId}/reviews/my`)
  }
}

// 收藏相关接口
export const favoriteApi = {
  // 收藏课程
  addFavorite(courseId: number): Promise<void> {
    return http.post(`/v1/favorites/${courseId}`)
  },

  // 取消收藏
  removeFavorite(courseId: number): Promise<void> {
    return http.delete(`/v1/favorites/${courseId}`)
  },

  // 检查收藏状态
  checkFavoriteStatus(courseId: number): Promise<boolean> {
    return http.get(`/v1/favorites/${courseId}/status`)
  },

  // 获取我的收藏
  getMyFavorites(page = 1, pageSize = 10): Promise<any> {
    return http.get('/v1/favorites/my', { params: { page, pageSize } })
  }
}

// 选课相关接口
export const enrollmentApi = {
  // 选课
  enrollCourse(courseId: number): Promise<void> {
    return http.post(`/v1/enrollments/${courseId}`)
  },

  // 取消选课
  unenrollCourse(courseId: number): Promise<void> {
    return http.delete(`/v1/enrollments/${courseId}`)
  },

  // 检查选课状态
  checkEnrollmentStatus(courseId: number): Promise<boolean> {
    return http.get(`/v1/enrollments/${courseId}/status`)
  },

  // 获取我的选课
  getMyEnrollments(page = 1, pageSize = 10): Promise<any> {
    return http.get('/v1/enrollments/my', { params: { page, pageSize } })
  }
}


